package r2dbc;
/**
 * 演示基于R2DBC的查询代码
 */

import io.r2dbc.spi.*;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import java.util.function.BiFunction;
import java.util.function.Function;
public class R2dbcDemo {
    public static void main(String[] args) throws Exception{
        String url="r2dbc:mysql://root:123@localhost:3306/my_db";
        String sql="SELECT id, name FROM accounts";
        //Connection Map 成为 Result
        Function<Connection,Publisher<? extends Result>> mapper1 =
                (Connection connection) -> connection.createStatement(sql).execute();
        //Result Map 成为 Account
        BiFunction<Row,RowMetadata,Account> mapper2=
                (Row row, RowMetadata metadata)->
                        new Account(row.get("id",Integer.class),row.get("name",String.class));

        // 创建连接工厂
        ConnectionFactory connectionFactory = ConnectionFactories.get(url);
        // 执行查询(基于Publisher建立Flux)
        Flux.from(connectionFactory.create())
                //基于Statement的查询，建立Flux
                .flatMap(mapper1)
                .flatMap(result -> result.map(mapper2))
                .subscribe(System.out::println);
        System.out.println("查询已经发送，等结果中。。。");
        System.in.read();
    }
}
